import { io } from "socket.io-client";
import { usePchatStore } from "@/stores/pchat";
const pchatStore = usePchatStore();
const OnEventConst = {
    CONNECT: "connect",
    DISCONNECT: "disconnect",
    CLOSE: "close",
    ERROR: "error",
    CONNECT_ERROR: "connect_error",
    CONNECT_TIMEOUT: "connect_timeout",
    PERSON_MESSAGE: "personMessage",
    GET_HISTORY: "getPersonHistory",
};
const EmitEventConst = {
    PERSON_MESSAGE: "personMessage",
    GET_HISTORY: "getPersonHistory",
};

export function connectSocket(userId) {
    const socket = io(`https://${location.host}?userId=${userId}`
        , {
        ackTimeout: 10000,
        retries: 5,
        autoConnect: true,
        transports: ['websocket'],
        withCredentials: true,
    });
   
    //监听接收历史消息
    socket.on(OnEventConst.GET_HISTORY, (data) => {
        const arrays = JSON.parse(data); 
        //由于按时间查的，倒序插入
        arrays.forEach((item) => {
            pchatStore.leftAdd(item);
        });
    });

    socket.on(OnEventConst.CONNECT, () => {
        console.log("socket connected");
    });
    socket.on(OnEventConst.CLOSE, () => {
        console.log("socket closed");
    }); 
    socket.on(OnEventConst.DISCONNECT, () => {
        pchatStore.removeInfo();
    });
    socket.on(OnEventConst.ERROR, (error) => {
        console.log("socket error", error);
    });
    socket.on(OnEventConst.CONNECT_ERROR, (error) => {
        console.log("socket connect error", error);
    });
    socket.on(OnEventConst.CONNECT_TIMEOUT, (timeout) => {
        console.log("socket connect timeout", timeout);
    });

    return socket;
}

export function disconnectSocket(socket) {
    if (socket) {
        socket.disconnect();
    }
}

export function sendMsgPerson(socket, data) {
    if (socket) {
        socket.emit(EmitEventConst.PERSON_MESSAGE, JSON.stringify(data), function (data) {
            console.log(data);
        });
    }
}

export function getHistory(socket, data) {
    if (socket) {
        socket.emit(EmitEventConst.GET_HISTORY, JSON.stringify(data), function (data) {
        });
    }
}